package proiect.fis.persistence;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Boogie
 */
public abstract class DaoImpl<T, PK extends Serializable> implements Dao<T, PK> {

    private Class type;
    protected EntityManager em;
    protected EntityManagerFactory emf;

    public DaoImpl(Class type, EntityManagerFactory emf) {
        this.emf = emf;
        em = emf.createEntityManager();
        this.type = type;
    }

    @Override
    public T delete(PK id) {
        T o = null;
        o = (T) em.find(type, id);
        this.delete(o);
        return o;
    }

    @Override
    public T delete(T item) {
        em.getTransaction().begin();
        em.remove(item);
        em.getTransaction().commit();
        return item;
    }

    @Override
    public List<T> delete(List<T> items) {
        em.getTransaction().begin();
        for (T item : items) {
            em.remove(item);
        }
        em.getTransaction().commit();
        return items;
    }

    @Override
    public T load(PK id) {
        T o = null;
        o = (T) em.find(type, id);
        return o;
    }

    @Override
    public abstract List<T> loadAll();

    @Override
    public void refresh(T item) {
        em.refresh(em);
    }

    @Override
    public void save(T item) {
        em.getTransaction().begin();
        em.persist(item);
        em.getTransaction().commit();
    }

    @Override
    public void saveAll(List<T> items) {
        em.getTransaction().begin();
        for (T item : items) {
            em.persist(item);
        }
        em.getTransaction().commit();
    }

    @Override
    public void update(T item) {

        em.getTransaction().begin();
        em.merge(item);
        em.getTransaction().commit();
    }

    @Override
    public void updateAll(List<T> items) {
        em.getTransaction().begin();
        for (T item : items) {
            em.merge(item);
        }
        em.getTransaction().commit();
    }
}
